﻿using DeviceMonitor.Classes;
using DeviceMonitor.Classes.Model;
using DeviceMonitor.Model;
using DeviceMonitor.ViewModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WebSocketSharp;

namespace DeviceMonitor.Pages
{
    /// <summary>
    /// MonitorPage.xaml 的交互逻辑
    /// </summary>
    public partial class MonitorPage : Page
    {
        //GroupViewModel viewModel;
        MonitorViewModel monitorViewModel;
        delegate void MessageDelegate(Object value);
        MessageDelegate d;
        WebSocket ws;
        private String deviceGroupCode = "01";
        public MonitorPage()
        {
            InitializeComponent();
            d = new MessageDelegate(setMessage);

            monitorViewModel = new MonitorViewModel();
            this.DataContext = monitorViewModel;

            deviceGroupCode = App.globalDeviceGroupCode;
            loadData();

            this.Loaded += Monitor_Loaded;
            this.Unloaded += Monitor_UnLoaded;
        }

        private void loadData()
        {
            monitorViewModel.items.Clear();
            
            if ("01".Equals(deviceGroupCode))
            {
                monitorViewModel.devicesTable01 = new Hashtable();
            }else if ("02".Equals(deviceGroupCode))
            {
                monitorViewModel.devicesTable02 = new Hashtable();
            }
            else if ("03".Equals(deviceGroupCode))
            {
                monitorViewModel.devicesTable03 = new Hashtable();
            }
            String deviceCodes = ConfigurationManager.AppSettings["deviceGroup_"+ deviceGroupCode + "_Codes"];
            if(null == deviceCodes)
            {
                deviceCodes = "";
            }
            int idxCode = 0;
            String[] deviceCode = deviceCodes.Split(',');
            foreach (String code in deviceCode)
            {
                ItemViewModel item = new ItemViewModel() { Code = code };
                monitorViewModel.items.Add(item);
                if ("01".Equals(deviceGroupCode))
                {
                    monitorViewModel.devicesTable01.Add(code, idxCode);
                }
                else if ("02".Equals(deviceGroupCode))
                {
                    monitorViewModel.devicesTable02.Add(code, idxCode);
                }
                else if ("03".Equals(deviceGroupCode))
                {
                    monitorViewModel.devicesTable03.Add(code, idxCode);
                }

                idxCode++;
            }
            
        }

        private void Monitor_Loaded(object sender, RoutedEventArgs e)
        {
            ws = new WebSocket(App.GetConfig().webSocket);
            ws.OnMessage += wsOnMessageReceive;
            ws.Connect();
        }
        private void Monitor_UnLoaded(object sender, RoutedEventArgs e)
        {
            ws.OnMessage -= wsOnMessageReceive;
            ws.Close();
        }
        void wsOnMessageReceive(object sender, MessageEventArgs e)
        {
            this.Dispatcher.Invoke(d, e.Data);
        }

        private void Server_sendMsgEvent(Object msg)
        {
            MessageDelegate d = new MessageDelegate(setMessage);
            this.Dispatcher.Invoke(d, msg);
        }
        
        Object getMessageObject(Object objStr)
        {
            Object obj = null;
            try
            {
                JObject jsonObj = JObject.Parse(objStr.ToString());
                int type = (int)jsonObj.GetValue("type");
                if (type == 62)
                {
                    obj = JsonConvert.DeserializeObject<Message62>(jsonObj.GetValue("data").ToString());
                }
                else if (type == 63)
                {
                    obj = JsonConvert.DeserializeObject<Message63>(jsonObj.GetValue("data").ToString());
                }
            }catch (Exception ex) { }
            return obj;
        }
        void setMessage(Object respString)
        {
            try
            {
                Object message = getMessageObject(respString);
                if (message.GetType() == typeof(Message62))
                {
                    Message62 msg = (Message62)message;
                    int sevIndex = msg.ServiceIndex;
                    String id = msg.Id.ToString();
                    String deviceCode = msg.DeviceCode;

                    int deviceIndex = -1;
                    if ("01".Equals(deviceGroupCode))
                    {
                        if (!monitorViewModel.devicesTable01.ContainsKey(deviceCode))
                        {
                            return;
                        }
                        deviceIndex = (int)monitorViewModel.devicesTable01[deviceCode];
                    }
                    else if ("02".Equals(deviceGroupCode))
                    {
                        if (!monitorViewModel.devicesTable02.ContainsKey(deviceCode))
                        {
                            return;
                        }
                        deviceIndex = (int)monitorViewModel.devicesTable02[deviceCode];
                    }
                    else if ("03".Equals(deviceGroupCode))
                    {
                        if (!monitorViewModel.devicesTable03.ContainsKey(deviceCode))
                        {
                            return;
                        }
                        deviceIndex = (int)monitorViewModel.devicesTable03[deviceCode];
                    }
                    if (deviceIndex == -1) return;

                    ItemViewModel item = monitorViewModel.items[deviceIndex];

                    item.ShouldNum = msg.ShouldVolume.ToString("0.0");
                    item.ActNum = msg.ActVolume.ToString("0.0");
                    item.Flow = msg.Flow.ToString("0.000");
                    item.Temperature = msg.Temp.ToString("0.00");
                    item.Density = msg.Density.ToString("0.0000");
                    item.Status = msg.Status;
                    item.Alerm = msg.Alerm;

                    item.CarNo = msg.CarNo;
                    item.Product = msg.Product;

                    item.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff:ffffff");
                }
                else if (message.GetType() == typeof(Message63))
                {
                    Message63 msg = (Message63)message;
                    int sevIndex = msg.ServiceIndex;
                    String deviceCode = msg.DeviceCode;

                    int deviceIndex = -1;
                    if ("01".Equals(deviceGroupCode))
                    {
                        if (!monitorViewModel.devicesTable01.ContainsKey(deviceCode))
                        {
                            return;
                        }
                        deviceIndex = (int)monitorViewModel.devicesTable01[deviceCode];
                    }
                    else if ("02".Equals(deviceGroupCode))
                    {
                        if (!monitorViewModel.devicesTable02.ContainsKey(deviceCode))
                        {
                            return;
                        }
                        deviceIndex = (int)monitorViewModel.devicesTable02[deviceCode];
                    }
                    else if ("03".Equals(deviceGroupCode))
                    {
                        if (!monitorViewModel.devicesTable03.ContainsKey(deviceCode))
                        {
                            return;
                        }
                        deviceIndex = (int)monitorViewModel.devicesTable03[deviceCode];
                    }
                    if (deviceIndex == -1) return;

                    ItemViewModel item = monitorViewModel.items[deviceIndex];

                    item.Status = "0";
                    item.Alerm = "00000000";

                    item.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff:ffffff");
                }
            }catch (Exception ex)
            {

            }
        }
    }
}
